<script setup>
    import coachApi from '@/api/coach.js'
    import {ref, reactive} from 'vue'
    import {
        Delete, Edit, Plus, Pointer, Postcard,
    } from '@element-plus/icons-vue'
    import {ElMessage, ElMessageBox} from 'element-plus'
    import {zhCn} from "element-plus/es/locale/index";
    import WangEditor from "@/components/WangEditor.vue";
    import {useTokenStore} from "@/store/token.js";

    //表格数据
    const list = ref([])
    const total = ref(0)
    //分页信息和搜索条件
    const coachQuery = reactive({
        name: '',
        phone: '',
        email: '',
        gender: '',
        introduction:'',
        page: 1,
        limit: 10
    })

    const loadData = () => {
        coachApi.page(coachQuery).then(result => {
            console.log(result)
            list.value = result.data.records
            total.value = result.data.total
        })
    }

    loadData()

    const loadMore = () => {
        coachApi.list().then(result => {
            console.log(result)
            list.value = result.data
            total.value = result.data.length
            coachQuery.page = 1
            coachQuery.limit = result.data.length
        })
    }

    const onSearch = () => {
        coachQuery.page = 1
        loadData()
    }

    const onRest = () => {
        coachQuery.name = ''
        coachQuery.phone = ''
        coachQuery.email = ''
        coachQuery.gender = ''
        coachQuery.introduction = ''
        coachQuery.page = 1
        loadData()
    }

    //根据id删除
    const deleteById = (id) => {
        ElMessageBox.confirm(
            '您确认要删除么?',
            '警告',
            {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
                lockScroll: false //防止抖动
            }
        ).then(() => {
            coachApi.deleteById(id).then(result => {
                if (result.code === 0) {
                    ElMessage({message: result.msg, type: 'success'})
                } else {
                    ElMessage.error(result.msg)
                }
                loadData()
            })
        })
    }

    const ids = ref([])
    const handleSelectionChange = (rows) => {
        console.log('多选', rows)
        //将多选的id放入数组中
        ids.value = rows.map(row => row.id)
        console.log(ids.value)
    }

    const deleteAll = () => {
        ElMessageBox.confirm(
            '您确认要删除么?',
            '警告',
            {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
                lockScroll: false //防止抖动
            }
        ).then(() => {
            coachApi.deleteAll(ids.value).then(result => {
                if (result.code === 0) {
                    ElMessage({message: result.msg, type: 'success',})
                } else {
                    ElMessage.error(result.msg)
                }
                loadData()
            })
        })
    }

    //分页|全部
    const isShowAll = ref(false)

    function handleShowAll() {
        isShowAll.value = true
        loadMore()
    }

    function handleShowPage() {
        coachQuery.page = 1
        coachQuery.limit = 10
        isShowAll.value = false
        loadData()
    }

    //添加、编辑
    const dialogFormVisible = ref(false)
    const coach = ref({})
    const title = ref()

    const showAddDialog = () => {
        dialogFormVisible.value = true
        title.value = '添加'
        coach.value = {}
        coach.value.status = 1
    }

    const showUpdateDialog = (id) => {
        dialogFormVisible.value = true
        title.value = '编辑'
        coach.value = {}
        coachApi.selectById(id).then(result => {
            coach.value = result.data
        })
    }

    const dialogIntroductionVisible = ref(false)
    const introduction = ref('')
    const showIntroduction = (intro) => {
        dialogIntroductionVisible.value = true
        introduction.value = intro
    }

    const addOrUpdate = () => {
        if (coach.value.id) {//编辑
            coachApi.update(coach.value).then(result => {
                if (result.code === 0) {
                    ElMessage({message: result.msg, type: 'success'})
                    dialogFormVisible.value = false
                } else {
                    ElMessage.error(result.msg)
                }
                loadData()
            })
        } else {//添加
            coachApi.add(coach.value).then(result => {
                if (result.code === 0) {
                    ElMessage({message: result.msg, type: 'success'})
                    dialogFormVisible.value = false
                } else {
                    ElMessage.error(result.msg)
                }
                loadData()
            })
        }
    }

    const handleSwitchChange = (row) => {
        coachApi.update(row).then(result => {
            if (result.code === 0) {
                ElMessage({message: result.msg, type: 'success'})
            } else {
                ElMessage.error(result.msg)
            }
            loadData()
        })
    }

    //图片上传
    const handleAvatarSuccess = (result) => {
        coach.value.avatar = result.data
    }
    const tokenStore = useTokenStore()
    const headers = ref({
        Authorization: tokenStore.token
    })

    //富文本编辑器
    const onEditorChange = (introduction) => {
        console.log(introduction)
        coach.value.introduction = introduction
    }

    const stripHtml = (html) => {
        return html?.replace(/<[^>]+>/g, '') || ''
    }
</script>

<template>
    <el-card class="">
        <template #header>
            <div class="header">
                <el-button type="primary" @click="showAddDialog">添加</el-button>
                <el-button type="primary" @click="deleteAll">批量删除</el-button>
                <el-button
                    class="fixed-width-btn"
                    :type="isShowAll ? 'info' : 'primary'"
                    @click="isShowAll ? handleShowPage() : handleShowAll()"
                >
                    <el-icon><Pointer/></el-icon>&nbsp;
                    {{ isShowAll ? '分页显示' : '显示全部' }}
                </el-button>
            </div>
        </template>
        <el-form :inline="true">
            <el-form-item label="名字">
                <el-input v-model="coachQuery.name" placeholder="请输入名字" clearable/>
            </el-form-item>
            <el-form-item label="手机号">
                <el-input v-model="coachQuery.phone" placeholder="请输入手机号" clearable/>
            </el-form-item>
            <el-form-item label="邮箱">
                <el-input v-model="coachQuery.email" placeholder="请输入邮箱" clearable/>
            </el-form-item>
            <el-form-item label="性别" w-auto="w-auto">
                <el-select v-model="coachQuery.gender" placeholder="请选择性别" clearable style="width: 120px">
                    <el-option label="男" value="男"/>
                    <el-option label="女" value="女"/>
                </el-select>
            </el-form-item>
            <el-form-item label="技能">
                <el-input v-model="coachQuery.introduction" placeholder="请输入技能" clearable/>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="onSearch">搜索</el-button>
                <el-button type="primary" @click="onRest">清空</el-button>
            </el-form-item>
        </el-form>
        <el-table :data="list" style="width: 100%" ref="multipleTableRef" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="60" />
            <el-table-column fixed prop="id" label="ID" width="60"/>
            <el-table-column prop="name" label="名字" width="100"/>
            <el-table-column prop="image" label="头像" width="80">
                <template #default="{ row }">
                    <img :src="row.avatar" alt="" style="height: 40px; width: auto; border-radius: 50%">
                </template>
            </el-table-column>
            <el-table-column prop="gender" label="性别" width="80"/>
            <el-table-column prop="introduction" label="简介" width="120">
                <template #default="{ row }">
                    <div
                        v-html="stripHtml(row.introduction).slice(0, 5) + ' ...'"
                        class="simple-html"
                    />
                </template>
            </el-table-column>
            <el-table-column prop="password" label="密码" width="100"/>
            <el-table-column prop="phone" label="电话" width="150"/>
            <el-table-column prop="email" label="邮箱" width="220"/>
            <el-table-column prop="status" label="状态">
                <template #default="scope">
                    <el-switch
                        v-model="scope.row.status"
                        size="large"
                        style="--el-switch-on-color: #44cef6; --el-switch-off-color: #ff2d51"
                        inline-prompt
                        :active-value="1"
                        :inactive-value="0"
                        active-text="激活"
                        inactive-text="封禁"
                        @change="handleSwitchChange(scope.row)"
                    />
                </template>
            </el-table-column>
            <el-table-column prop="createTime" label="创建时间" width="190"/>
            <el-table-column prop="updateTime" label="更新时间" width="190"/>
            <el-table-column fixed="right" label="操作" width="200">
                <template #default="{ row }">
                    <el-button type="primary" :icon="Edit" circle @click="showUpdateDialog(row.id)"/>
                    <el-button type="success" :icon="Postcard" circle @click="showIntroduction(row.introduction)"/>
                    <el-button type="danger" :icon="Delete" circle @click="deleteById(row.id)"/>
                </template>
            </el-table-column>
        </el-table>
        <el-config-provider :locale="zhCn">
            <el-pagination
                v-model:current-page="coachQuery.page"
                v-model:page-size="coachQuery.limit"
                :page-sizes="[10, 20, 30, 40]"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
                @change="loadData"
                style="margin-top: 20px; justify-content: flex-end"
            />
        </el-config-provider>
    </el-card>

    <!--添加、编辑弹出框-->
    <el-dialog v-model="dialogFormVisible" :title="title" width="600" :lock-scroll="false">
        <el-form :model="coach">
            <el-form-item label="名字" :label-width="60">
                <el-input v-model="coach.name" autocomplete="off" />
            </el-form-item>
            <el-form-item label="头像" :label-width="60">
                <el-upload
                    class="avatar-uploader"
                    action="/api/upload"
                    :headers="headers"
                    :show-file-list="false"
                    :on-success="handleAvatarSuccess"
                >
                    <img v-if="coach.avatar" :src="coach.avatar" class="avatar" />
                    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                    <template #tip>
                        <div class="el-upload__tip">
                            可以上传png/jpg/gif等格式的图片资源，且不超过5mb
                        </div>
                    </template>
                </el-upload>
            </el-form-item>
            <el-form-item label="性别" :label-width="60">
                <el-select v-model="coach.gender" placeholder="请选择性别" clearable style="width: 120px">
                    <el-option label="男" value="男"/>
                    <el-option label="女" value="女"/>
                </el-select>
            </el-form-item>
            <el-form-item label="状态" :label-width="60">
                <el-switch
                    v-model="coach.status"
                    size="large"
                    style="--el-switch-on-color: #44cef6; --el-switch-off-color: #ff2d51"
                    inline-prompt
                    :active-value="1"
                    :inactive-value="0"
                    active-text="激活"
                    inactive-text="封禁"
                />
            </el-form-item>
            <el-form-item label="密码" :label-width="60">
                <el-input v-model="coach.password" autocomplete="off" />
            </el-form-item>
            <el-form-item label="邮箱" :label-width="60">
                <el-input v-model="coach.email" autocomplete="off" />
            </el-form-item>
            <el-form-item label="手机" :label-width="60">
                <el-input v-model="coach.phone" autocomplete="off" />
            </el-form-item>
            <el-form-item label="简介" :label-width="60">
                <WangEditor
                    :initValue="coach.introduction"
                    @getEditorContent="onEditorChange"
                    v-if="dialogFormVisible"
                    @close="dialogFormVisible = false"
                />
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取消</el-button>
                <el-button type="primary" @click="addOrUpdate">确认</el-button>
            </div>
        </template>
    </el-dialog>

    <el-dialog
        v-model="dialogIntroductionVisible"
        width="40%"
        :lock-scroll="false"
        align-center
        draggable
    >
        <div v-html="introduction"></div>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialogIntroductionVisible = false">确认</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<style scoped>
    .fixed-width-btn {
        width: 100px;
        text-align: center;
        transition: none !important;
    }

    .avatar-uploader {
        border-color: var(--el-color-primary);
    }
    .el-icon.avatar-uploader-icon {
        border: 2px dashed var(--el-border-color);
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
        transition: var(--el-transition-duration-fast);
    }

    .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 178px;
        height: 178px;
        text-align: center;
    }

    .avatar{
        width: 178px;
        height: 178px;
        display: block;
    }
</style>